package edu.univercidade.tcc.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import edu.univercidade.tcc.server.model.ProjectMember;

@RooWebScaffold(path = "projectmembers", formBackingObject = ProjectMember.class)
@RequestMapping("/projectmembers")
@Controller
public class ProjectMemberController {

	@RequestMapping(method = RequestMethod.PUT)
	public String update(@Valid ProjectMember projectMember,
			BindingResult bindingResult, Model uiModel,
			HttpServletRequest httpServletRequest) {
		if (projectMember.getHashedPassword() == null
				|| projectMember.getHashedPassword().isEmpty()) {
			projectMember.setHashedPassword(projectMemberService
					.getPassWord(projectMember));
		}

		if (bindingResult.hasErrors()) {
			uiModel.addAttribute("projectMember", projectMember);
			addDateTimeFormatPatterns(uiModel);
			return "projectmembers/update";
		}
		uiModel.asMap().clear();
		projectMemberService.updateProjectMember(projectMember);
		return "redirect:/projectmembers/"
				+ encodeUrlPathSegment(projectMember.getId().toString(),
						httpServletRequest);
	}

	@RequestMapping(params = "password", method = RequestMethod.GET)
	public String passwordForm(Model uiModel,
			HttpServletRequest httpServletRequest) {
		uiModel.addAttribute("projectMember",
				projectMemberService.getUserByLogin(httpServletRequest
						.getUserPrincipal().getName()));
		addDateTimeFormatPatterns(uiModel);
		return "projectmembers/password";
	}
	
	@RequestMapping(value ="/password", method = RequestMethod.PUT)
	public String password(@Valid ProjectMember projectMember,
			BindingResult bindingResult, Model uiModel,
			HttpServletRequest httpServletRequest) {
		ProjectMember persisted = projectMemberService.findProjectMember(projectMember.getId());
		persisted.setHashedPassword(projectMember.getHashedPassword());
		uiModel.asMap().clear();
		projectMemberService.updatePassword(persisted);
		return "redirect:/projectmembers/"
				+ encodeUrlPathSegment(projectMember.getId().toString(),
						httpServletRequest);
	}

}
